#include "StdAfx.h"
#include <iostream>
#include "XMLDocument.h"
#include <xercesc\sax\HandlerBase.hpp>

CXMLDocument::CXMLDocument(void)
{
	m_pDocument = NULL;
}

CXMLDocument::~CXMLDocument(void)
{
	if (m_pDocument!=NULL)
	{
		m_pDocument->release();
		m_pDocument = NULL;
	}
}

CXMLDocument* CXMLDocument::Read(string filename)
{
	XercesDOMParser* parser = new XercesDOMParser();
	parser->setValidationScheme(XercesDOMParser::Val_Always);
	parser->setDoNamespaces(true);    // optional

	ErrorHandler* errHandler = (ErrorHandler*) new HandlerBase();
	parser->setErrorHandler(errHandler);

	try {
		parser->parse(filename.c_str());
		CXMLDocument* xmlDocument = new CXMLDocument();
		xmlDocument->m_pDocument = parser->getDocument();
	}
	catch (const XMLException& toCatch) {
		char* message = XMLString::transcode(toCatch.getMessage());
		std::cerr<< "Exception message is: \n"
			<< message << "\n";
		XMLString::release(&message);
		return NULL;
	}
	catch (const DOMException& toCatch) {
		char* message = XMLString::transcode(toCatch.msg);
		std::cerr<< "Exception message is: \n"
			<< message << "\n";
		XMLString::release(&message);
		return NULL;
	}
	catch (...) {
		std::cerr<< "Unexpected Exception \n" ;
		return NULL;
	}

	delete parser;
	delete errHandler;
	return NULL;
}

//CXMLDocument* CXMLDocument::Read()
//{
//	DOMElement* child_element;
//	CXMLDocument doc;
//	return NULL;
//}

CXMLDocument* CXMLDocument::Create(string filename)
{
	CXMLDocument doc;
	return &doc;
}

string CXMLDocument::XMLCh_to_string(const XMLCh* in)
{
	char* s = XMLString::transcode(in);
	string r(s);
	XMLString::release(&s);
	return r;
}

double CXMLDocument::string_to_double(string s)
{  
	istringstream instr(s);
	double x;
	instr >> x;
	return x;
}

int CXMLDocument::string_to_int(string s)
{  
	istringstream instr(s);
	int x;
	instr >> x;
	return x;
}